package com.goldsign.pay.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.goldsign.pay.common.to.ServiceResponseDTO;
import com.goldsign.pay.common.util.rsa.RsaEncrypt;
import com.goldsign.pay.common.util.rsa.RsaUtils;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 
 * @author xiaoxianwen
 *
 */
public class SignUtil {
	/**
	 * 组装签名原文
	 * @param serviceResponseDTO
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String signText(ServiceResponseDTO serviceResponseDTO) throws Exception{
		JSONObject json = (JSONObject)JSON.toJSON(serviceResponseDTO);
		String[] fieldNames = getFiledName(serviceResponseDTO);
		List<String> plist = new ArrayList<String>();
		for (int i = 0; i < fieldNames.length; i++) {
			if("sign".equals(fieldNames[i])) {
				continue;
			}
			plist.add(fieldNames[i]);
		}
		Collections.sort(plist);
		StringBuilder sb=new StringBuilder();
		for(int i =0;i<plist.size();i++){
			sb.append(plist.get(i));
			sb.append("=");
			sb.append(json.get(plist.get(i)));
			if(i==plist.size()-1){
				continue;
			}
			sb.append("&");
		} 
		System.out.println("MD5前【sb.toString()】:"+ sb.toString());
		System.out.println("MD5后【sb.toString()】:"+ Md5.md5_32(sb.toString()));
		return Md5.md5_32(sb.toString());
	}
	/**
	 * 获取对象属性名数组
	 * @param o
	 * @return
	 */
	public static String[] getFiledName(Object o){ 
	    Field[] fields=o.getClass().getDeclaredFields();  
	        String[] fieldNames=new String[fields.length];  
	    for(int i=0;i<fields.length;i++){  
	        System.out.println(fields[i].getType());  
	        fieldNames[i]=fields[i].getName();  
	    }  
	    return fieldNames;  
	   } 
	
	public static String signResponse(ServiceResponseDTO serviceResponseDTO) {
		String str = "";
		try {
			byte[] data = signText(serviceResponseDTO).getBytes();
			String publicKey = RsaEncrypt.loadKeyByClasspath("PublicKey_ser.keystore");
			byte[] rt_data = RsaUtils.encryptByPublicKey(data, publicKey);
			str = Base64Utils.encode(rt_data);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  str;
	}
}
